package com.eco.fanliapp.job.historypricejob;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.SyGoodsHistoryPrices;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.ApiUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.vo.HistoryContentVo;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取商品最低价
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HistoryLowPriceTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(HistoryLowPriceTask.class);


    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private ISyGoodsHistoryPricesService iSyGoodsHistoryPricesService;


    public HistoryLowPriceTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执获取订单商品基本信息定时任务-HistoryLowPriceTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        try {
            Page<AppGoods> page = new Page<>(1, 100000);
            QueryWrapper<AppGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("item_top", 1).eq("recommend",1).orderByDesc("update_time");
            IPage<AppGoods> appGoodsIPage = iAppGoodsService.page(page, queryWrapper);

            if (appGoodsIPage != null && appGoodsIPage.getRecords() != null) {
                for (AppGoods appGoods : appGoodsIPage.getRecords()) {
                    Map<String, Object> data = new HashMap<String, Object>();
                    data.put("itemid", appGoods.getItemid());

                    //拉取商品历史价格
                    String str = ApiUtils.getDataHistory(data);
                    JSONObject jsonObject = JSONObject.parseObject(str);
                    String historyData = jsonObject.getString("sales_record");
                    if (historyData != "" || historyData != null) ;
                    List<HistoryContentVo> response = JsonUtils.getJsonToList(historyData, HistoryContentVo.class);

                    for (HistoryContentVo history : response) {
                        SyGoodsHistoryPrices syGoodsHistoryPrices = new SyGoodsHistoryPrices();
                        syGoodsHistoryPrices.setItemId(appGoods.getItemid());
                        syGoodsHistoryPrices.setItemPrice(history.getItemendprice());
                        syGoodsHistoryPrices.setItemPriceDate(DateFormatUtils.string2date(history.getTime()));
                        syGoodsHistoryPrices.setCreateTime(new Date());
                        syGoodsHistoryPrices.setUpdateTime(new Date());
                        syGoodsHistoryPrices.setEnable(1);
                        syGoodsHistoryPrices.setDeleted(0);
                        int i = iSyGoodsHistoryPricesService.add(syGoodsHistoryPrices);
                        if (i > 0) {
                            log.info("历史价格添加成功");
                        } else {
                            log.info("历史价格添加失败");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取订单商品基本信息错误");
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行获取订单商品基本信息定时任务-MessagePushTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - beginTime));

    }
}
